#pragma once
#include <iostream>
#include <vector>
#include <semaphore.h>
#include <pthread.h>

using namespace std;

const static int defaultcap = 5;

template <class T>
class RingQueue
{
private:
    void P(sem_t &sem)
    {
        sem_wait(&sem);
    }
    void V(sem_t &sem)
    {
        sem_post(&sem);
    }
    void Lock(pthread_mutex_t &mutex)
    {
        pthread_mutex_lock(&mutex);
    }
    void Unlock(pthread_mutex_t &mutex)
    {
        pthread_mutex_unlock(&mutex);
    }

public:
    RingQueue(int cap = defaultcap)
        : _ringqueue(cap), _cap(cap), _c_step(0), _p_step(0)
    {
        sem_init(&_cdata_sem, 0, 0);
        sem_init(&_pspace_sem, 0, cap);

        pthread_mutex_init(&_c_mutex, nullptr);
        pthread_mutex_init(&_p_mutex, nullptr);
    }

    void Push(const T &in) // 生产
    {
        P(_pspace_sem);

        Lock(_p_mutex);
        _ringqueue[_p_step] = in;
        // 位置后移，维持环形特征
        _p_step++;
        _p_step %= _cap;
        Unlock(_p_mutex);
        V(_cdata_sem);
    }

    void Pop(T *out) // 消费
    {
        P(_cdata_sem);

        Lock(_c_mutex);
        *out = _ringqueue[_c_step];
        // 位置后移，维持环形特征
        _c_step++;
        _c_step %= _cap;
        Unlock(_c_mutex);

        V(_pspace_sem);
    }

    ~RingQueue()
    {
        sem_destroy(&_cdata_sem);
        sem_destroy(&_pspace_sem);

        pthread_mutex_destroy(&_c_mutex);
        pthread_mutex_destroy(&_p_mutex);
    }

private:
    vector<T> _ringqueue;
    int _cap;

    int _c_step; // 消费者下标
    int _p_step; // 生产者下标

    sem_t _cdata_sem;  // 消费者关注的数据资源
    sem_t _pspace_sem; // 生产者关注的资源

    pthread_mutex_t _c_mutex;
    pthread_mutex_t _p_mutex;
};